import axios from 'axios'
import router from '@/router'
import {
	ElMessage
} from 'element-plus'
import store from '@/store' // 直接导入 store 实例
// 创建axios实例
const request = axios.create({
	baseURL: store.state.request_url + '/api/v1',
	timeout: 600000
})

// 是否正在跳转登录页的标志
let isRedirecting = false
// 请求拦截器
request.interceptors.request.use(
	config => {
		const token = localStorage.getItem('token')
		if (token) {
			config.headers['Authorization'] = `Bearer ${token}`
		}
		return config
	},
	error => {
		return Promise.reject(error)
	}
)

// 响应拦截器
request.interceptors.response.use(
	response => {
		return response
	},
	error => {
		let errorMessage = '网络请求出错';
		if (!error.response) {
			errorMessage = '网络错误，请检查网络连接'
			return Promise.reject(error)
		}
		const {status} = error.response
		if (error !== undefined) {
			switch (status) {
				case 400:
					errorMessage = '请求错误';
					break;
				case 401:
					if (isRedirecting) {
						return Promise.reject(error);
					}
					isRedirecting = true
					localStorage.removeItem('token')
					if (router.currentRoute.value.path != '/login') {
						errorMessage='登录已过期，请重新登录'
						store.commit('Login_dialog_show')
					}
					setTimeout(() => {
						isRedirecting = false;
					}, 1000);
					break;
				case 403:
					errorMessage = '拒绝访问';
					break;
				case 404:
					errorMessage = '请求出错';
					break;
				case 408:
					errorMessage = '请求超时';
					break;
				case 429:
					errorMessage = '请求频繁, 请稍后再访问';
					break;
				case 500:
					errorMessage = '服务器开小差啦,请稍后再试~';
					break;
				case 501:
					errorMessage = '服务未实现';
					break;
				case 502:
					errorMessage = '网络错误';
					break;
				case 503:
					errorMessage = '服务不可用';
					break;
				case 504:
					errorMessage = '网络超时';
					break;
				case 505:
					errorMessage = 'HTTP 版本不受支持';
					break;
			}
			// if (error.response.data?.msg.includes('timeout')) errorMessage = '请求超时';
		}
		if (error && error.config) {
			ElMessage.error(errorMessage ||error.response.data?.msg)
		}
		return Promise.reject(error)
	}
)

export default request